package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApAssociateWordsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        searchRequest.source().size(0);
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        suggestBuilder.addSuggestion("articleSuggest",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(dto.getSearchWords()).skipDuplicates(true).size(10));
        searchRequest.source().suggest(suggestBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析数据
        CompletionSuggestion completionSuggestion = response.getSuggest().getSuggestion("articleSuggest");
        List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
        List<String> list = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option option : options) {
            list.add(option.getText().string());
        }
        return ResponseResult.okResult(list);
    }
}
